package com.mvc.config;

import com.alibaba.fastjson2.JSON;
import com.mvc.common.IgnoreResponseForRes;
import com.mvc.common.Res;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回结果封装
 * @author JayEinstein
 */
@RestControllerAdvice(basePackages = "com.mvc.controller")
public class ResponseForResAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        // controller返回的是Res类型略过
        if (returnType.getParameterType().isAssignableFrom(Res.class)) {
            return false;
        }

        // 拥有IgnoreResponseForRes注解不进行自动封装
        if (returnType.hasMethodAnnotation(IgnoreResponseForRes.class)) {
            return false;
        }

        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        // 返回的结果是字符串类型，需要手动改成json
        if (returnType.getParameterType().isAssignableFrom(String.class)) {
            // 设置响应的类型为JSON
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            return JSON.toJSONString(Res.ok(body));
        }

        return Res.ok(body);
    }

}
